#include "PlayerManager.hpp"

PlayerManager::PlayerManager(){
    Player registerPlayer;
	registerObject(&registerPlayer);
}

/**
 * Initialize manager with size s players.
 */
void PlayerManager::init(byte s){
    size = s;
    players = new Player*[size];
    for(unsigned short i = 0; i < s; i++){
        players[i] = 0;
    }
	ObjectManager::init("Objects/s_players.lua");
}

void PlayerManager::update(unsigned int frameTime){
     for(unsigned short i = 0; i < size; i++){
         if(players[i] && !players[i]->destroy)
             runUpdate(players[i]);
     }
}

/**
 * Run startup script on passed player.
 */
void PlayerManager::createPlayer(Player* player){
    player->destroy = BaseObject::d_Clean;
    runStartup(player, "player");
    players[player->index] = player;
}

/**
 * Run destroy script on passed player.
 * Since players are stored in the client collections and
 * never deleted we do not have to worry about destroy states.
 */
void PlayerManager::destroyPlayer(Player* player){
    player->destroy = BaseObject::d_Destroy;
    runDestroy(player);
    players[player->index] = 0;
}

void PlayerManager::bind(lua_State* luaState){
	luabind::module(luaState)[
        luabind::class_<PlayerManager>("Manager")
			.def_readonly("size", &PlayerManager::size)
    ];
}

void PlayerManager::push(lua_State* luaState){
	luabind::object o = luabind::object(luaState, this);
    o.push(luaState);
}